package me.xuym.crawler.dygang.loader;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.network.HttpClient;
import com.cbs.java.component.network.Request;
import com.cbs.java.component.network.Response;
import com.cbs.java.component.network.decoder.GsonDecoder;
import com.google.gson.reflect.TypeToken;
import me.xuym.crawler.Processor;
import me.xuym.crawler.dygang.entity.DYGangDBResult;
import me.xuym.crawler.dygang.entity.DoubanResult;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by broche on 14/09/2017.
 */
public class DoubanLoader extends Processor<List<DYGangDBResult>, List<DYGangDBResult>> {
    private HttpClient httpClient = new HttpClient.Builder().build();

    public DoubanLoader(Application application) {
        super(application);
    }

    @Override
    protected List<DYGangDBResult> onProcess(List<DYGangDBResult> dyGangDBResults) throws Exception {
        for (DYGangDBResult result : dyGangDBResults) {
            Request request = new Request(String.format("https://movie.douban.com/j/subject_suggest?q=%s", result.getName()))
                    .setDecoder(new GsonDecoder(new TypeToken<List<DoubanResult>>() {
                    }.getType()));
            Response response = httpClient.sendSync(request);
            List<DoubanResult> dbResults = (List<DoubanResult>) response.getResult();
            if (dbResults.size() > 0) {
                result.setDburl(dbResults.get(0).getUrl());
                result.setDbname(dbResults.get(0).getTitle());

                Request request2 = new Request(String.format("https://movie.douban.com/subject/%s/", dbResults.get(0).getId()));
                Response response2 = httpClient.sendSync(request2);
                String content = (String) response2.getResult();
                result.setDbcollection(getVoteNumber(content));
                result.setDbrating(getRating(content));
            }
        }
        return dyGangDBResults;
    }

    private int getVoteNumber(String content) {
        int voteNumber = 0;
        Pattern pattern = Pattern.compile("<span property=\"v:votes\">([0-9]+?)</span>");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            voteNumber = Integer.valueOf(matcher.group(1).trim());
        }
        return voteNumber;
    }

    private float getRating(String content) {
        float rating = 0.0f;
        Pattern pattern = Pattern.compile("property=\"v:average\">([0-9|\\.]+?)</strong>");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            rating = Float.valueOf(matcher.group(1));
        }
        return rating;
    }
}
